<template>
  <div class="article-list">
    <van-pull-refresh v-model="isLoading" @refresh="refresh">
      <van-list
        v-if="bol"
        v-model="loading"
        :finished="finished"
        finished-text="已经没有更多数据了！"
        @load="getData"
      >
        <article-item v-for="item in list" :key="item.art_id" :item="item" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import ArticleItem from './article-item.vue'
import { articles } from '@/api/home.js'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    id: {
      type: Number
    }
  },
  data () {
    return {
      bol: true,
      isLoading: false,
      loading: false,
      finished: false,
      list: [],
      // 定义时间戳，请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳
      timestamp: Date.now()
    }
  },
  created () {
    // this.getData()
  },
  methods: {
    async getData () {
      const res = await articles({
        channel_id: this.id,
        timestamp: this.timestamp
      })
      // 调用接口完成后数据累加处理,...arr数组的结构
      this.list.push(...res.data.results)
      // 将本组件的isloading改为false
      this.loading = false
      // 如果有返回值的时间戳,说明有下一页,存储调用下一页,没值就加载完成
      if (res.data.pre_timestamp) {
        this.timestamp = res.data.pre_timestamp
      } else {
        this.finished = true
      }
      console.log('获取文章新闻推荐res:', res)
    },
    // 下拉刷新
    async refresh () {
      // 1.还原上拉加载的属性
      this.loading = false
      this.finished = false
      // 2.调用第一页的数据,时间戳还原
      this.list = []
      this.timestamp = Date.now()
      // 3.加入await,保证接口调用完成后再做下一步
      await this.getData()
      // 4.将下拉刷新的属性改为false
      this.isLoading = false
      // 5.将van-list组件初始化一次
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    }
  }
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  // Y轴滚动条
  overflow-y: auto;
  padding: 0 16px;
}
</style>
